// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
// import FastClick from 'fastclick'
import App from './App'
import router from './router/index'
import 'font-awesome/css/font-awesome.min.css'

import axios from 'axios'

import { Loading ,LoadingPlugin,Toast,ToastPlugin } from 'vux'
Vue.component('loading', Loading)
Vue.component('toast', Toast)
Vue.use(LoadingPlugin)
Vue.use(ToastPlugin)
import store from './vuex/store.js'

//后台传json
import qs from 'qs'
Vue.prototype.$qs = qs;
//模拟数据
// import Mock from './mock/index'
// Mock.test()
// FastClick.attach(document.body)

Vue.config.productionTip = false


axios.interceptors.request.use(function (config) {
  Vue.$vux.loading.show({text: '数据加载中'})

  return config
}, function (error) {
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
  Vue.$vux.loading.hide()

  return response
}, function (error) {
  Vue.$vux.loading.hide()

  Vue.$vux.toast.show({
    text: '网络异常',
    position: 'middle',
    type: 'cancel'
  })

  return Promise.reject(error)
})


router.beforeEach((to,from,next) => {
  next()
  // Vue.$vux.loading.show();
  let user = sessionStorage.getItem('userInfo');
  //如果要跳到登录页面，就清空用户信息
  if (to.path=='/login') {
    sessionStorage.removeItem('userInfo');
    next()
  }

  if (to.matched.some((r)=>r.meta.requireAuth)) {
    //判断用户是否登陆
    if (user) { 
      if (Object.keys(from.query).length===0) { //判断是不是有前一个页面
        next();
      }else{
        let redirect = from.query.redirect;
        if (to.path===redirect) {
          next() //解决next无限循环
        }else{
          next({path:redirect}); //跳转到目的路由
        }
      }
    }else{
      if (to.path == '/login') { //用户没登陆，要跳转到login页面
        next();
      }
      else{ //用户没登陆，要跳转到需要登陆的的页面，就把上一个页面的值传进url中，并跳转到login页面
        next({
          path:"/login",
          query:{
            redirect: to.fullPath //http://localhost:8080/login?redirect=%2Froles
          }
        })
      }
    }  
  }else{
    next()
  }
  
  
  
})


/* eslint-disable no-new */
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app-box')
